<!--
 * @Description: 站点配合比
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:23:36
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display:flex">
        <div v-loading="treeLoading" class="tree">
          <el-tree ref="tree" :data="treeData" default-expand-all :expand-on-click-node="false">
            <span slot-scope="{ node,data }" class="custom-tree-node tree-line">
              <span v-if="data.children">
                <i :class="data.icon"></i>
                <span>{{ node.label }}</span>
              </span>
              <el-radio-group v-else v-model="activetree" @change="fromDate.pointName=data.label, pointName=data.label">
                <el-radio :label="data.value">
                  <span>{{ node.label }}</span>
                </el-radio>
              </el-radio-group>
            </span>
          </el-tree>
        </div>
        <div class="card_bg">
          <div class="card scroll">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="addFromDate('添加')">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
              </div>
              <div></div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <span v-if="item.label == '序号'">{{scope.$index+1}}</span>
                      <span v-else-if="item.label == '操作'">
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" class="bottom_one" size="mini" @click="datails(scope.row,0)">
                          <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                          修改
                        </el-button>
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" size="mini" class="bottom_two" @click="Update2(scope.row)">
                          <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                          删除
                        </el-button>
                      </span>

                      <span v-else-if="item.label == '配合比'">
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='CHAKANPHB'))!==-1" class="bottom_one" size="mini" @click="datails(scope.row,1)">查看配合比</el-button>
                      </span>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
          <div class="card_bottom">
            <div class="card_bottom_left">
              <div class="top_page_totle">总共{{ total }}条</div>
              <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
            </div>
            <div>
              <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
            </div>
          </div>
        </div>

      </el-main>

    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="880px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div>
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="80px">
          <el-form-item prop="effectTime">
            <span slot="label">生效日期</span>
            <el-date-picker v-model="fromDate.effectTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
          <div>
            <el-form-item>
              <el-button size="mini" class="bottom_all" style="margin-left: 0;" @click="addItem()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
            </el-form-item>
          </div>
          <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="fromDate.itemList" tooltip-effect="dark">
            <el-table-column align="center" label="原物料">
              <template slot-scope="scope">
                <el-select v-model="scope.row.materialId" placeholder="请选择" style="width:100%">
                  <el-option v-for="(item, index) in arr1" :key="index" :label="item.itemName" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="配合比">
              <template slot-scope="scope">
                <el-input v-model="scope.row.radioValue" style="width:100%" placeholder="请输入" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.radioValue=$regExp.checkNum(scope.row.radioValue)" @blur="scope.row.radioValue=$regExp.blurCheckNum(scope.row.radioValue)">
                  <template slot="append">kg/m<sup>3</sup></template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="误差范围">
              <template slot-scope="scope">
                <el-input v-model="scope.row.errorRange" type="Number" style="width:100%" placeholder="请输入" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.errorRange=$regExp.checkNum(scope.row.errorRange)" @blur="scope.row.errorRange=$regExp.blurCheckNum(scope.row.errorRange)">
                  <template slot="append">kg/m<sup>3</sup></template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" class="bottom_two" @click="delItem(scope.$index)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看配合比 -->
    <el-dialog v-dialogDrag :visible.sync="Dialog1" width="880px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看配合比</span>
      <div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="fromDate.itemList" tooltip-effect="dark">
          <el-table-column align="center" label="原物料" prop="materialName"></el-table-column>
          <el-table-column slot-scope align="center" label="配合比" prop="radioValue">
            <span slot="header">配合比(kg/m<sup>3</sup>)</span>
          </el-table-column>
          <el-table-column align="center" label="误差范围" prop="errorRange">
            <span slot="header">误差范围(kg/m<sup>3</sup>)</span>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="Dialog1=false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import { queryPage, itemList, query_pagedeletes } from "@/api/basicConfig/mix.js";
// import { queryMaterialsPage } from "@/api/basicConfig/Rmaterial.js";
import { getDicType } from "@/api/common.js";
import { getUserAutList } from "@/api/common.js";
export default {
  mixins: [mixin],
  data() {
    return {
      UserInfo: '',
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      /*表格数据*/
      table: [
        { label: "序号", width: "auto", prop: "", status: true },
        { label: "配合比", width: "auto", prop: "", status: true },
        { label: "生效日期", width: "auto", prop: "effectTime", status: true },
        { label: "操作", width: "200", prop: "", status: true },
      ],
      /*表单页类型，0为无树状，1为有树状，有树状在el-main加上display:flex
       */
      treeData: [],
      activetree: "",
      pagesType: 1,
      /*添加表单数据*/
      rules: {
        effectTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
      },
      fromDate: {
        effectTime: "",
        pointId: "",
        pointName: '',
        itemList: [],
      },
      pointName: '',
      oldarr: [],
      arr1: [],
      Dialog1: false,
      stationIdlist: [],
    };
  },
  async created() {
    this.treeData = await getUserAutList()
    this.activetree = this.treeData[0].children[0].value;
    this.fromDate.pointName = this.treeData[0].children[0].label;
    this.pointName = this.treeData[0].children[0].label;
    this.treeLoading = false;
    getDicType({ code: "MATname" }).then((res) => {
      this.arr1 = res.data.items;
    });
  },
  watch: {
    activetree: {
      handler() {
        this.tableParam.pointId = this.activetree;
        this.gettableData();
      },
      deep: false,
      immediate: true,
    },
  },
  /*
   *copy(data)深拷贝数据,返回拷贝完的数据
   *gettableData获取列表数据
   *load下载
   *SortNum保持序列号
   * UpdateOrDelete禁用，启用，删除
   * submitFromDate保存更新数据
   */
  methods: {
    Update2(row) {
      this.$confirm('此操作将永久删除该信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'bottom_all_two',
        confirmButtonClass: 'bottom_all',
        type: 'warning'
      })
        .then(() => {
          let json = {
            ids: [row.id],
            status: 0
          }
          query_pagedeletes(json).then((res) => {
            if (res.code == 1001) {
              this.gettableData();
            }
          })
        })
        .catch(() => { });
    },
    init() {
      this.getStation();
    },
    datails(low, type) {
      itemList({ settingsId: low.id }).then((res) => {
        this.fromDate.itemList = res.data;
        if (type == 0) {
          this.activetree = low.pointId;
          this.fromDate.effectTime = low.effectTime;
          this.oldarr = this.copy(res.data);
          this.updateFromDate(this.fromDate, "修改");
        } else {
          this.Dialog1 = true;
        }
      });
    },
    addItem() {
      let data = {
        materialId: "",
        radioValue: "",
        errorRange: "",
      };
      this.fromDate.itemList.push(data);
    },
    delItem(index) {
      this.fromDate.itemList.splice(index, 1);
    },
    pagessubmitFromDate() {
      let _this = this;
      _this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          if (_this.fromDate.itemList.length == 0) {
            _this.$message({
              message: "至少添加一项配合比",
              type: "warning",
            });
            return;
          }
          const newData = _this.fromDate.itemList.some(item => item.materialId === '' || item.radioValue === '' || item.errorRange === '')
          if (newData) {
            this.$message.warning('添加的原物料数据不能为空')
            return
          }
          if ([...new Set(_this.fromDate.itemList.map((item) => item.materialId))].length < _this.fromDate.itemList.length) {
            this.$message.warning('添加的原物料名称不能相同');
            return;
          }
          const key = _this.fromDate.itemList.map((res) => {
            return res.materialId;
          });
          const key1 = new Set(key);
          if (key.length !== key1.size) {
            _this.$message({
              message: "请删除重复原物料",
              type: "warning",
            });
            return;
          }
          _this.fromDate.itemList.forEach((res) => {
            res.materialName = _this.$fromatTable(
              _this.arr1,
              res.materialId,
              "id",
              "itemName"
            );
          });
          let allHasData = _this.fromDate.itemList.filter((item) =>
            _this.oldarr.some((items) => item.id == items.id)
          );
          let deleteData = _this.oldarr.filter(
            (item) => !allHasData.some((items) => item.id == items.id)
          );
          let addData = _this.fromDate.itemList.filter(
            (item) => !allHasData.some((items) => item.id == items.id)
          );
          deleteData.forEach((res) => {
            res.status = 0;
          });
          _this.fromDate.itemList = [...allHasData, ...deleteData, ...addData];
          _this.fromDate.pointId = _this.activetree;
          _this.fromDate.pointName = _this.pointName;
          _this.addDialog = false;
          _this.$router.push({ name: "sign_mix", query: { id: JSON.stringify(_this.fromDate), type: 1, copyTableData:  JSON.stringify(_this.oldarr)} });
        } else {
          return false;
        }
      });
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
</style>
